import { RenderSystem } from './RenderSystem.js';
import { Building, BuildingType } from '../entities/Building.js';

// 基础实体接口
export interface Entity {
    id: string;
    x: number;
    y: number;
    width: number;
    height: number;
    active: boolean;
    
    update(deltaTime: number): void;
    render(renderSystem: RenderSystem): void;
    destroy(): void;
}

// 网格占用信息
interface GridCell {
    occupied: boolean;
    entityId: string | null;
}

export class EntitySystem {
    private entities: Map<string, Entity> = new Map();
    private entityCounter: number = 0;
    private defenseGrid: GridCell[][];
    private lastInterceptorLog: number = 0; // 🔍 用于控制拦截器日志输出频率

    constructor() {
        // 初始化防御网格
        this.defenseGrid = [];
        for (let row = 0; row < 7; row++) {
            this.defenseGrid[row] = [];
            for (let col = 0; col < 5; col++) {
                this.defenseGrid[row][col] = {
                    occupied: false,
                    entityId: null
                };
            }
        }
    }

    async init(): Promise<void> {
        console.log('🎯 初始化实体系统...');
        
        // 创建一些测试实体
        this.createTestEntities();
        
        console.log('✅ 实体系统初始化完成');
    }

    update(deltaTime: number): void {
        // 更新所有实体
        for (const entity of this.entities.values()) {
            if (entity.active) {
                entity.update(deltaTime);
            }
        }

        // 清理已销毁的实体
        this.cleanupDestroyedEntities();
    }

    render(renderSystem: RenderSystem): void {
        // 渲染所有实体
        let interceptorCount = 0;
        for (const entity of this.entities.values()) {
            if (entity.active) {
                // 🔍 统计拦截器数量
                if (entity.constructor.name === 'Interceptor') {
                    interceptorCount++;
                }
                entity.render(renderSystem);
            }
        }
        
        // 🔍 每秒输出一次拦截器数量（仅在有拦截器时）
        if (interceptorCount > 0) {
            const now = Date.now();
            if (!this.lastInterceptorLog || now - this.lastInterceptorLog > 1000) {
                console.log(`🎯 EntitySystem 正在渲染 ${interceptorCount} 个拦截器`);
                this.lastInterceptorLog = now;
            }
        }
    }

    private createTestEntities(): void {
        // 创建一些测试实体，展示基本功能
        
        // 在伊朗区域创建发射场标识
        this.addEntity(new TestLaunchSite('launch-site-1', 75, 100));
        this.addEntity(new TestLaunchSite('launch-site-2', 75, 200));
        
        // 在防御区域创建重要建筑物（真实的可被攻击建筑）
        this.addEntity(new Building('government-building', BuildingType.GOVERNMENT, 1050, 300));
        this.addEntity(new Building('airport', BuildingType.AIRPORT, 1100, 500));
        this.addEntity(new Building('port', BuildingType.PORT, 950, 600));
        this.addEntity(new Building('residential-1', BuildingType.RESIDENTIAL, 1000, 450));
        this.addEntity(new Building('military-base', BuildingType.MILITARY, 1150, 350));
        
        console.log('🏢 创建了5个可攻击的建筑物目标');
    }

    // 获取所有建筑物（用于导弹碰撞检测）
    public getBuildings(): Building[] {
        return this.getEntitiesOfType(Building);
    }

    // 检查导弹是否击中建筑物
    public checkMissileHitBuildings(missileX: number, missileY: number, damage: number): Building | null {
        const buildings = this.getBuildings();
        
        for (const building of buildings) {
            if (building.active && building.isInBounds(missileX, missileY)) {
                const destroyed = building.takeDamage(damage, 'missile');
                return building; // 返回被击中的建筑
            }
        }
        
        return null; // 没有击中任何建筑
    }

    private cleanupDestroyedEntities(): void {
        for (const [id, entity] of this.entities.entries()) {
            if (!entity.active) {
                entity.destroy();
                this.entities.delete(id);
            }
        }
    }

    // 实体管理方法
    public addEntity(entity: Entity): void {
        this.entities.set(entity.id, entity);
    }

    public removeEntity(id: string): void {
        const entity = this.entities.get(id);
        if (entity) {
            entity.active = false;
        }
    }

    public getEntity(id: string): Entity | undefined {
        return this.entities.get(id);
    }

    public getAllEntities(): Entity[] {
        return Array.from(this.entities.values());
    }

    public getEntitiesOfType<T extends Entity>(type: new (...args: any[]) => T): T[] {
        return Array.from(this.entities.values()).filter(entity => entity instanceof type) as T[];
    }

    // 网格管理方法
    public isGridOccupied(gridX: number, gridY: number): boolean {
        if (gridX < 0 || gridX >= 5 || gridY < 0 || gridY >= 7) {
            return true; // 边界外视为占用
        }
        return this.defenseGrid[gridY][gridX].occupied;
    }

    public occupyGrid(gridX: number, gridY: number, entityId?: string): void {
        if (gridX >= 0 && gridX < 5 && gridY >= 0 && gridY < 7) {
            this.defenseGrid[gridY][gridX].occupied = true;
            this.defenseGrid[gridY][gridX].entityId = entityId || null;
        }
    }

    public freeGrid(gridX: number, gridY: number): void {
        if (gridX >= 0 && gridX < 5 && gridY >= 0 && gridY < 7) {
            this.defenseGrid[gridY][gridX].occupied = false;
            this.defenseGrid[gridY][gridX].entityId = null;
        }
    }

    public getGridEntity(gridX: number, gridY: number): string | null {
        if (gridX >= 0 && gridX < 5 && gridY >= 0 && gridY < 7) {
            return this.defenseGrid[gridY][gridX].entityId;
        }
        return null;
    }

    // 辅助方法
    public generateEntityId(): string {
        return `entity_${++this.entityCounter}`;
    }

    public getEntityCount(): number {
        return this.entities.size;
    }

    public getActiveEntityCount(): number {
        return Array.from(this.entities.values()).filter(entity => entity.active).length;
    }
}

// 测试实体类
class TestLaunchSite implements Entity {
    public id: string;
    public x: number;
    public y: number;
    public width: number = 40;
    public height: number = 60;
    public active: boolean = true;

    constructor(id: string, x: number, y: number) {
        this.id = id;
        this.x = x;
        this.y = y;
    }

    update(deltaTime: number): void {
        // 简单的闪烁效果
    }

    render(renderSystem: RenderSystem): void {
        // 渲染发射场
        renderSystem.renderEntity(this.x, this.y, this.width, this.height, '#7B2D26');
        
        // 添加标识
        renderSystem.renderText('🚀', this.x - 10, this.y - 30, 'white', '20px Arial');
        renderSystem.renderText('发射场', this.x - 15, this.y + 35, 'white', '10px Arial');
    }

    destroy(): void {
        // 清理资源
    }
}
